import {messages, simplifyDataSource} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import {Radio} from 'antd';
import SlideFrame from 'components/slide-frame'
import 'styles/financial-management/supplier-management/supplier-management.scss'
import moment from 'moment'
import ExportModal from "components/template/export-modal/export-modal";
import NewUpdateManagement from 'containers/setting/feedback-management/feedback-management-detail'
import FeedbackManagementService from 'containers/setting/feedback-management/feedback-management.service'
import feedbackService from 'containers/feedback/feedback.service';
import AdvancedTable from 'components/advanced-table'
import menuRoute from 'routes/menuRoute';
const { SimpleTable } = AdvancedTable;

const statusMap = {
  '-1': messages('common.all')/*全部*/,
  '0': messages('basic-4.key1')/*待处理*/,
  '1': messages('basic-4.key2')/*受理中*/,
  '2': messages('basic-4.key3')/*等待回复*/,
  '3': messages('basic-4.key4')/*已解决*/,
  '99': messages('basic-4.key5')/*已关闭*/
}

class FeedbackManagement extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      data: [],
      searchParams:{},
      searchForm: [
        { id: 'feedbackNo', dataIndex: "feedbackNo", label: messages('basic-4.key21')/*流水号*/, component: 'Input',},
        { id: 'keyword', dataIndex: "issueContent", label: messages('basic-4.key42')/*反馈内容*/, component: 'Input', },
        {
          id: 'dateRange', label: messages('basic-4.key25')/*提交时间*/, component: 'DateRangePicker',
          dataIndex: 'createdDate',
          props: {
            placeholder: messages('basic-4.key48')/*请选择temp*/,
          },
          parser: value => ({
            startDate: (value && value[0]) ? value[0].utc().format() : null,
            endDate: (value && value[1]) ? value[1].utc().format() : null
          })
        },
        {
          id: 'status',
          label: messages('common.column.status')/*状态*/,
          dataIndex: 'status',
          component:
            <Radio.Group>
              {
                Object.keys(statusMap).map(item => <Radio value={item}>{statusMap[item]}</Radio>)
              }
            </Radio.Group>,
        },
        {
          id: 'userId',
          label: messages('basic-4.key44')/*反馈人员*/,
          component: 'Chooser',
          dataIndex: 'username',
          props: {
            placeholder: messages('basic-4.key48')/*请选择temp*/,
            type: 'user',
            showSearch: true,
            listType: 'user',
            single: true,
            labelKey: 'fullName',
            valueKey: 'id',
            searchIfKeywordIsNull: true,
            listExtraParams: {
              status: 'all'
            }
          },
          parser: value => {
            if (value && value.length)
              return {userId: value[0].id}
          }
        }
      ],
      columns: [],
    }
  }

  componentWillMount() {
    this.renderDataSource();
  };

  renderDataSource = () => {
    let dataSource = [
      {feedbackNo: messages('basic-4.key21')/*流水号*/, width: 140},
      {modules: messages('basic-4.key22')/*模块*/, width: 140, render: text => text ? text.map(item=>item.name).join(',') : "-"},
      {issueContent: messages('basic-4.key42')/*反馈内容*/, width: 500},
      {username: messages('basic-4.key44')/*反馈人员*/, width: 140},
      {tags: messages('common.label')/*标签*/, width: 140, render: text => text ? text.map(item=>item.name).join(',') : "-"},
      {clients: messages('basic-4.key23')/*渠道*/, width: 140, render: text =>  text ? text.map(item=>item.name).join(',') : "-"},
      {status: messages('common.column.status')/*状态*/, width: 100, render: text => text ? statusMap[text] : '-'},
      {createdDate: messages('basic-4.key25')/*提交时间*/, width: 140, render: text => text ? moment(text).format("YYYY-MM-DD") : null},
    ];
    let columns = simplifyDataSource(dataSource);

    this.setState({
      columns
    }, () => {
      this.renderSearchForm();
    })
  };

  renderSearchForm = () => {
    const {searchForm} = this.state;
    feedbackService.getIssueItems({codes: ['MODULE', 'TAG', 'CHANNEL']}).then(res => {
      if(res.data){
        let json = {
          MODULE: {
            id: 'moduleIds',
            label: messages('basic-4.key22')/*模块*/,
            dataIndex: 'modules',
          },
          CHANNEL: {
            id: 'clientIds',
            label: messages('basic-4.key23')/*渠道*/,
            dataIndex: 'clients',
          },
          TAG: {
            id: 'tagIds',
            label: messages('common.label')/*标签*/,
            dataIndex: 'tags',
          }
        };

        let arr = [];
        for(let attr in res.data){
          arr.push(
            {
              id: json[attr].id,
              label: json[attr].label,
              dataIndex: json[attr].dataIndex,
              component:
                <Radio.Group>
                  {
                    res.data[attr].map(item => <Radio value={item.id}>{item.name}</Radio>)
                  }
                </Radio.Group>,
            }
          )
        }
        this.setState({ searchForm: searchForm.concat(arr) });
      }
    })
  };

  service = (page, size, searchParams) => {
    let params = Object.assign({page, size}, searchParams);
    this.setState({ searchParams });
    for (let paramsName in params) {
      !params[paramsName] && delete params[paramsName];
    }
    if (params.status === '-1') {
      delete params.status;
    } else {
      params.states = params.status;
      delete params.status;
    }
    return FeedbackManagementService.getFeedbackList(params)
      .then((response) => {
      return response;
    })
  };

  renderBasicSettingSlide = (config) => {
    let {title, params} = config;
    return {
      title,
      content: NewUpdateManagement,
      params,
      afterClose: this.afterClose,
    }
  };

  editItem = (e, record) => {
    this.context.router.push(menuRoute.getPageUrlByKey("customer-feedback-detail").replace(':id', record.id));
    // let params = {
    //   title: messages('basic-4.key42')/*反馈内容*/,
    //   params: {id: record.id},
    // }, that = this;
    // SlideFrame.open(that.renderBasicSettingSlide(params), this)
  };

  afterClose = () => {
    this.advancedTableRef.getList()
  };

  render() {
    const { loading, searchForm, columns, searchParams } = this.state;
    return (
      <div className="feedback-management">
        {
          searchForm.length >= 6 &&
            <div className="full-height-page">
          <SimpleTable
            loading={loading}
            onRef={ref => this.advancedTableRef = ref}
            title={messages('basic-4.key49')/*反馈管理*/}
            searchForm={searchForm}
            columns={columns}
            tableName={'feedback-management-table'}
            show={['table-utils']}
            service={this.service}
            onRow={record => ({onClick: (e) => {this.editItem(e, record)}})}
            rowKey="id"
          >
            <ExportModal
              type="btn"
              btnType="primary"
              codeCheck={true}
              exportTitle={messages('basic-4.key50')/*导出数据*/}
              exportType="OPERATION_FEEDBACK"
              exportCondition={{
                feedbackNo: searchParams.feedbackNo,
                keyword: searchParams.keyword,
                startDate: searchParams.startDate,
                endDate: searchParams.endDate,
                moduleIds: searchParams.moduleIds ? [searchParams.moduleIds] : null,
                clientIds: searchParams.clientIds ? [searchParams.clientIds] : null,
                tagIds: searchParams.tagIds ? [searchParams.tagIds] : null,
              }}
              exportCommand={"operation_feedback_info"}/>
          </SimpleTable>
            </div>
        }
      </div>
    )
  }
}

FeedbackManagement.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    main: state.main,
    authToken: state.main.authToken,
    tenantMode: state.main.tenantMode,
    user: state.login.user,
    menuPermission: state.main.menuPermission,
  }
}

export default connect(mapStateToProps)(FeedbackManagement);
